<template>
  <div class="left" ref="playClick">
    <!-- 搜索 -->
    <div class="left_botton mt-6">
      <div style="height: 35px;">
        <div style="width: 40%;float: left;" class="text-white text-2xl">患者管理 {{ patList.length }}</div>
        <div class="search" style="background: none;"></div>
        <div class="search">
          <el-input
            placeholder="姓名/床位号/身份证号"
            prefix-icon="search"
            v-model="keyWord"
            @input="searchByKey"
            @keyup.enter="getList"
            clearable
            @clear="getList"
          />
        </div>
        <div style="width: 9%;float: left;margin-left: 1%;" class="top_btn cursor-pointer" @click="stopScoll">
          {{ clickText }}
        </div>
        <div style="width: 9%;float: left;margin-left: 1%;" class="top_btn cursor-pointer" @click="stopPlayAideo">
          {{ playAideo }}
        </div>
      </div>
      <!-- 滚动数据 -->
      <Vue3SeamlessScroll
        class="scroll"
        :step="scrollOption.step"
        :list="patList"
        :isWatch="scrollOption.isWatch"
        :limitScrollNum="scrollOption.limitScrollNum"
        :wheel="scrollOption.wheel"
        :hover="scrollOption.hover"
      >
        <el-row>
          <el-col :span="12"
                  style="padding: 0px 0px 0px 10px"
                  v-for="(item, index) in patList"
                  :key="index">
            <div class="patient_item text-white cursor-pointer"
                 @click="handlePat(item, index)"
            >
              <div class="flex justify-center relative">
                <h1 class="text-2xl">{{ item.patientName }} -
                  {{ item.place }}</h1>
                <svg aria-hidden="true" class="w-6 h-6 absolute right-3">
                  <use xlink:href="#icon-patient_hosp"/>
                </svg>
              </div>
              <div class="flex mt-15 justify-around">
                <div class="w-2/4">
                  <div class="flex justify-between">
                    <div class="flex">
                      <svg aria-hidden="true" class="w-6 h-6">
                        <use xlink:href="#icon-mattress"/>
                      </svg>
                      <div class="ml-2 text-xl">床垫</div>
                    </div>
                    <span class="text-lg">{{ item.monitorPadScreenData?.acquisitionTime || '--' }}</span>
                  </div>
                  <div class="flex flex-wrap mt-3">
                    <div class="w-2/4">
                      <span class="text-lg">呼吸</span>
                      <span class="ml-8 text-lg font-bold">{{
                          item.monitorPadScreenData?.breathRate || '--'
                        }}</span>
                    </div>
                    <div class="w-2/4">
                      <span class="text-lg">心率</span>
                      <span class="ml-8 text-lg font-bold">{{
                          item.monitorPadScreenData?.heartRate || '--'
                        }}</span>
                    </div>
                    <div class="w-2/4">
                      <span class="text-lg">血氧</span>
                      <span class="ml-8 text-lg font-bold">{{ item.monitorPadScreenData?.spo2 || '--' }}</span>
                    </div>
                    <div class="w-2/4">
                      <span class="text-lg">体动</span>
                      <span class="ml-8 text-lg font-bold">{{
                          item.monitorPadScreenData?.bodyMove == '1'
                            ? '正常'
                            : item.monitorPadScreenData?.bodyMove == '2'
                              ? '体动'
                              : '--'
                        }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </Vue3SeamlessScroll>
    </div>
  </div>
  <div class="right ml-5">
    <!-- 异常数据 -->
    <div class="left_top flex justify-between">
      <div
        v-for="(item, index) in imgList"
        :key="index"
        :class="['left_top_item ', 'flex', 'items-center']"
        :style="[
          {
            backgroundImage:
              index == popoverIdx
                ? `url(${getImageUrl(styleOptine[popoverIdx][0])})`
                : `url(${getImageUrl('lsd_top_left.png')})`
          }
        ]"
        @click="handleBg(item, index)"
      >
        <img :src="getImageUrl(item.url)" alt="" class="ml-1.5 w-11 h-11"/>
        <div class="ml-3">
          <p class="text-2xl font-semibold text-white">{{ item.value }}</p>
          <p class="text-lg">{{ item.text }}</p>
        </div>
      </div>
      <!-- 弹出窗 -->
      <div class="popover" v-if="popoverIdx != 5">
        <div class="popover_item flex items-center">
          <div class="flex items-center">
            <svg aria-hidden="true" class="w-6 h-6 ml-2">
              <use :xlink:href="`#icon-${styleOptine[popoverIdx][1]}`"/>
            </svg>
            <span class="text-white">{{ styleOptine[popoverIdx][2] }}</span>
          </div>
          <div class="flex items-center ml-52">
            <img class="popover_zs" :src="getImageUrl(styleOptine[popoverIdx][3])" alt=""/>
            <svg aria-hidden="true" class="w-3 h-3 ml-4 cursor-pointer" @click="popoverIdx = 5">
              <use :xlink:href="`#icon-${styleOptine[popoverIdx][4]}`"/>
            </svg>
          </div>
        </div>
        <!-- 动画 -->
        <Decoration4 :reverse="true" style="width: 100%; height: 7px"/>
        <!-- 表格 -->
        <div class="tab mt-2">
          <el-table
            :data="
              popoverIdx == 0
                ? heartWarn
                : popoverIdx == 1
                ? spO2Warn
                : popoverIdx == 2
                ? breathWarn
                : []
            "
            style="width: 100%"
            :header-row-style="rowClass"
            :border="false"
            :max-height="710"
            @row-click="Rowclick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column
              prop="patientName"
              label="预警事由"
              width="140"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <span class="text-lg"
                      :style="(row.heartRate&&row.heartRate=='0')||(row.breathRate&&row.breathRate=='0')?'color: #f53f3f':'color: #E6A23C'">{{
                    (row.heartRate && row.heartRate == '0') || (row.breathRate && row.breathRate == '0') ? (0 == popoverIdx ? "心率为零" : "呼吸为零") : row.warnContent
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="patientName" label="姓名" width="80">
              <template #default="{ row }">
                <span class="text-lg">{{ row.patientName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="deptName" label="科室" width="100">
              <template #default="{ row }">
                <span class="text-lg">{{ row.deptName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bedNo" label="床位号" width="80">
              <template #default="{ row }">
                <span class="text-lg">{{ row.bedNo }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="预警时间" :show-overflow-tooltip="true">
              <template #default="{ row }">
                <span class="text-lg">{{ row.createTime }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- btn -->
        <div class="btn">
          <span
            class="btn_item cursor-pointer"
            :style="{ background: styleOptine[popoverIdx][5] }"
            @click="handleWarning(1)"
          >立即处理</span
          >
          <span class="btn_item cursor-pointer" @click="handleWarning(2)">稍后处理</span>
        </div>
      </div>
    </div>
  </div>
  <div class="drawer" style="background-color: black;">
    <el-drawer v-model="drawer" size="1250" direction="ltr" :with-header="false" @closed="closeDrawer" modal="false"
               style="background-color: black;">
      <RightTop/>
      <div class="abnormal mt-4 flex justify-between items-center">
        <div class="warning flex">
          <!--&nbsp;&nbsp;<span v-if="wranText != ''">此患者{{ wranText }} 请立即处理</span>-->
          &nbsp;&nbsp;<span class="text-xl" v-if="wranText != ''">此患者{{ wranText }}</span>
        </div>
        <div class="btn" v-if="wranText != ''">
          <span class="btn_item text-xl" @click="oneKeyhandleWarn(1)">一键处理异常</span>
        </div>
        <div class="btn pr-4">
          <el-date-picker
            @change="getList"
            v-model="dateTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </div>
      </div>
      <RightBotton/>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {onBeforeUnmount, reactive, ref} from 'vue'
import {formatTime, getImageUrl} from '@/utils'
import {Vue3SeamlessScroll} from 'vue3-seamless-scroll'
import {Decoration4} from '@kjgl77/datav-vue3'
import {getPat, getPatSign, getWarn, handleWarn, getPatWarn, handleAbnormal} from '@/api/lsd'
import {toRefs, watch} from 'vue'
import {useLsdStore} from '@/store/modules/lsd'
import {ElMessage} from 'element-plus'
import {storeToRefs} from 'pinia'
import RightTop from './rightTop.vue'
import RightBotton from './rightBotton.vue'
import warningSond from '@/assets/audio/warning_sond.mp3'

const wranText = ref('')
const useLsd = useLsdStore()
const {patActive} = storeToRefs(useLsd)

const scrollOption = reactive({
  // step: 0.8, //步进速度
  step: 0.3, //步进速度
  imgList: [],
  isWatch: true, //开启数据更新监听
  limitScrollNum: 5, //开启滚动的数据量，只有列表长度大于等于该值才会滚动
  wheel: true, //在开启鼠标悬停的情况下是否开启滚轮滚动
  hover: true //是否开启鼠标悬停
})
const clickText = ref("暂停滚动")
const playAideo = ref("开启警报")
const isPlayAudio = ref(false)
const stopScoll = () => {
  clickText.value = 0 == scrollOption.step ? "暂停滚动" : "开始滚动"
  scrollOption.step = 0 == scrollOption.step ? 0.3 : 0
}
const stopPlayAideo = () => {
  playAideo.value = isPlayAudio.value ? "开启警报" : "关闭警报"
  isPlayAudio.value = isPlayAudio.value ? false : true;
}
const drawer = ref(false)
const time: any = ref(null)
const patList: any = ref([]) //患者列表
const keyWord: any = ref('') //关键字
const hospital: any = ref('') //关键字
const warnData = reactive({
  heartWarn: [], //心率警告列表
  spO2Warn: [], //血氧浓度警告列表
  breathWarn: [] //呼吸率警告列表
})
const warnArr = ref([]) //处理预警数组
const patIdx = ref(0)

const {heartWarn, spO2Warn, breathWarn} = toRefs(warnData)
const popoverIdx = ref(0)

const warningAudio = new Audio()
warningAudio.src = warningSond

//预警样式
const styleOptine = reactive([
  ['hr_active.png', 'hr', '心率预警', 'hr_zs.png', 'purple_close', '#722ED1'],
  ['sa_active.png', 'hr', '血氧预警', 'sa_zs.png', 'pink_close', '#F5319D'],
  ['resp_active.png', 'hr', '呼吸预警', 'resp_zs.png', 'green_close', '#00B42A'],
  ['lsd_top_left', 'hr', '呼吸预警', 'hr_zs.png', 'purple_close', '#722ED1']
])

const imgList = reactive([
  {
    url: 'avgHr.png',
    text: '心率预警(条)',
    value: '0'
  },
  {
    url: 'avgSaO2.png',
    text: '血氧预警(条)',
    value: '0'
  },
  {
    url: 'resp.png',
    text: '呼吸预警(条)',
    value: '0'
  }
])

const rowClass = reactive({
  background: 'rgba(255, 255, 255, 0.1)',
  color: 'rgba(255, 255, 255, 0.7)'
})

//点击患者存储信息
const handlePat = (obj: any, idx: number) => {
  drawer.value = true
  useLsd.setPatActive(obj)
  getPatSignData(obj.visitNoStr)
  patIdx.value = idx
}

//改变预警背景
const handleBg = (e: any, idx: number) => {
  if (popoverIdx.value == idx) {
    // popoverIdx.value = 5
  } else {
    popoverIdx.value = idx
  }
}

const timeOut = ref();
const searchByKey = () => {
  if (timeOut.value) clearTimeout(timeOut.value);
  timeOut.value = setTimeout(() => {
    getList()
  }, 1000)
}

/** 查询患者列表 */
const getList = () => {
  getPat(keyWord.value, hospital.value).then((res: any) => {
    patList.value = res.data
    if (patList.value.length > 0) {
      useLsd.setPatActive(patList.value[patIdx.value]) //默认第一个
      getPatSignData(patList.value[patIdx.value].visitNoStr)
    }
  })
}

const closeDrawer = () => {
  time.value = [];
  dateTime.value = undefined;
}

const zeroTarget = (data) => {
  let zeroPlayAudio = false;
  data.forEach(order => {
    let mps = order.monitorPadScreenData;
    // let sbs = order.smartBraceletScreenData;
    if (mps && mps.sleepStatus
      && mps.sleepStatus == "4"//在床
    ) {
      for (var key in warnData) {
        if ("heartWarn" == key || "breathWarn" == key) {
          for (let i = 0; i < warnData[key].length; i++) {
            switch (key) {
              case "heartWarn":
                if (mps.equipmentNo == warnData[key][i].equipmentNo) {
                  heartWarn.value[i]['heartRate'] = "" + (mps.heartRate);
                  if (0 == mps.heartRate) zeroPlayAudio = true;
                }
                continue;
              case "breathWarn":
                if (mps.equipmentNo == warnData[key][i].equipmentNo) {
                  breathWarn.value[i]['breathRate'] = "" + (mps.breathRate);
                  if (0 == mps.breathRate) zeroPlayAudio = true;
                }
                continue;
            }
          }
        }
      }
    }
  })
  if (zeroPlayAudio && isPlayAudio.value) warningAudio.play();
}
/** 查询预警列表 */
const getWarnList = () => {
  getWarn().then((res: any) => {
    let {
      heartWarn: heartWarnRes,
      spO2Warn: spO2WarnRes,
      breathWarn: breathWarnRes
    } = res.data;
    if ((res.data.heartWarn && imgList[0].value != res.data.heartWarn.length)
      || (res.data.spO2Warn && imgList[1].value != res.data.spO2Warn.length)
      || (res.data.breathWarn && imgList[2].value != res.data.breathWarn.length)) {
      if (isPlayAudio.value) {
        // 播放
        warningAudio.play();
      }
    }
    heartWarn.value = heartWarnRes
    spO2Warn.value = spO2WarnRes
    breathWarn.value = breathWarnRes
    zeroTarget(patList.value)

    imgList[0].value = heartWarnRes?.length || 0
    imgList[1].value = spO2WarnRes?.length || 0
    imgList[2].value = breathWarnRes?.length || 0
  })
}


const dateTimeFormat = (timestamp) => {
  const date = new Date(timestamp);
  const Y = date.getFullYear() + '-';
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  const D = date.getDate() + ' ';
  const h = date.getHours() + ':';
  const m = date.getMinutes() + ':';
  const s = date.getSeconds();
  return Y + M + D + h + m + s;
}

const dateTime = ref<[string, string]>()

/** 就诊号查询患者体征数据 */
const getPatSignData = (patientIdStr: string) => {
  if (!drawer.value) return;//未展开抽屉，不查询相关数据
  const time = ref(dateTime.value);
  if (!dateTime.value) {
    let date = new Date();
    let dayBeforeTime = getTheDayBeforeTime(date);
    time.value = [
      dateTimeFormat(dayBeforeTime.getTime()),
      dateTimeFormat(date.getTime()),
    ];
    dateTime.value = [formatTime(dayBeforeTime, 'yyyy-MM-dd HH:mm:ss'), formatTime(date, 'yyyy-MM-dd HH:mm:ss')];
  }
  getPatSign(patientIdStr, time.value).then((res: any) => {
    if (res) useLsd.setPatData(res.data)
  })
}

// 获取指定日期的前一天18:00
const getTheDayBeforeTime = (currentTime: Date) => {
  let y = currentTime.getFullYear()
  let m = currentTime.getMonth() + 1
  let d = currentTime.getDate()
  if (d - 1 < 1) {
    if (m - 1 < 1) {
      y = y - 1
      m = 12
    } else {
      m = m - 1
    }
    d = new Date(y, m, 0).getDate()
  } else {
    d = d - 1
  }
  // 前一天的时间
  return new Date(y, m - 1, d, 18);
}


//点击预警表格
const Rowclick = (e) => {
  drawer.value = true
  keyWord.value = e.visitNoStr
  patIdx.value = 0
  getList()
}

//定时刷新预警
time.value = setInterval(() => {
  getList()
  getWarnList()
}, 15000)

const handleSelectionChange = (selection: any) => {
  selection.forEach((val) => {
    let data = {
      warnId: val.id, //预警id
      warnType: val.warnType, //预警类型
      handleWay: 1 //
    }
    warnArr.value.push(data)
  })
}

const handleWarning = (type: 1 | 2) => {
  if (warnArr.value.length <= 0) {
    ElMessage.error('请勾选需处理患者！')
    return
  }
  warnArr.value.forEach((val: any) => {
    val.handleWay = type
  })
  handleWarn(warnArr.value).then(() => {
    ElMessage.success('处理成功！')
    getWarnList()
  })
}
//页面销毁关闭定时器
onBeforeUnmount(() => {
  clearInterval(time.value)
  time.value = null
  console.log('页面注销了')
})
//监听选择患者变换
watch(patActive, (newValue) => {
  patWarn(newValue)
})

//当前患者的预警信息
const patWarn = (data) => {
  getPatWarn(data.visitNoStr).then((res: any) => {
    let str = ''
    res?.data.forEach((val) => {
      str += val.warnContent + ','
    })
    if (str != "") {
      str = str.substring(0, str.length - 1);
    }
    wranText.value = str
  })
}

//一键处理
const oneKeyhandleWarn = (type: 1 | 2) => {
  handleAbnormal({visitNo: patActive.value.visitNoStr, handleWay: type}).then((res: any) => {
    ElMessage.success('处理成功！')
    patWarn(patActive.value)
    wranText.value = ''
  })
}
getList()
getWarnList()
</script>

<style scoped lang="less">
.left {
  width: 1250px;

  .search {
    width: 19%;
    float: left;
    margin-left: 1%;
    height: 38px;
    background-image: url(@/assets/imgs/search.png);
    background-size: 100% 100%;
    background-position: center center;
  }

  .scroll {
    width: 100%;
    height: 870px;
    overflow: hidden;
    margin-top: 16px;
  }

  .patient_item {
    width: 100%;
    /*float: left;*/
    /*width: 910px;*/
    height: 250px;
    background-image: url(@/assets/imgs/patient2.png);
    background-size: 100% 100%;
    /*background-size: cover;*/
    /*background-position: center center;*/
    margin-bottom: 16px;
    // padding: 17px;
    padding: 30px 17px 17px 17px;;
    box-sizing: border-box;
    overflow: hidden;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -ms-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-perspective: 1000;
    -moz-perspective: 1000;
    -ms-perspective: 1000;
    perspective: 1000;
    /* Other transform properties here */
  }
}

.right {
  width: 621px;

  .left_top {
    position: relative;

    .left_top_item {
      width: 180px;
      height: 96px;
      background-size: 100% 100%;
      background-position: center center;
      color: #dfdfdf;
      cursor: pointer;
    }

    .popover {
      width: 100%;
      height: 840px;
      position: absolute;
      left: 0;
      top: 106px;
      background-image: url(@/assets/imgs/popover_bg.png);
      /*background-size: cover;*/
      background-size: 100% 100%;
      background-position: center center;
      z-index: 999;
      transition: 0.3s;

      .popover_item {
        width: 100%;
        height: 50px;

        .popover_zs {
          width: 250px;
          height: 22px;
        }
      }

      .btn {
        position: absolute;
        right: 0px;
        bottom: 18px;

        .btn_item {
          width: 88px;
          line-height: 32px;
          border-radius: 2px;
          color: #fff;
          background: rgba(255, 255, 255, 0.16);
          text-align: center;
          display: inline-block;
          margin-right: 17px;
        }
      }
    }
  }
}
</style>
<style lang="less">
.el-input__wrapper {
  height: 38px;
  background: none;
  border: none;
  border-radius: 0;
  box-shadow: none;
}

.tab {
  .el-table,
  th.el-table__cell,
  td.el-table__cell,
  .el-table__row {
    background-color: transparent !important;
    border-bottom: none !important;
    color: #fff;
  }

  .el-table__inner-wrapper::before {
    display: none;
  }
}

.el-drawer {
  background-color: black !important;
}

.top_btn {
  /*width: 104px;*/
  /*position: absolute;*/
  line-height: 35px;
  right: 16px;
  bottom: 20px;
  text-align: center;
  /*padding: 8px 16px;*/
  /*border-radius: 8px;*/
  background: rgba(0, 169, 145, 0.2);
  box-sizing: border-box;
  border: 1px solid #00a991;
  color: #00a991;
}

.abnormal {
  width: 100%;
  height: 48px;
  background-image: url(@/assets/imgs/abnormal_bg.png);
  background-size: cover;
  background-position: center center;

  .warning {
    color: #fff;
    width: 600px;

    span {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .btn {
    .btn_item {
      display: inline-block;
      width: 140px;
      line-height: 30px;
      text-align: center;
      color: #ed6a0c;
      border-radius: 4px;
      background: rgba(237, 106, 12, 0.2);
      margin-right: 16px;
      cursor: pointer;
    }
  }
}

.text-lg {
  font-size: 1rem;
  line-height: 1.5rem
}

/*.drawer >>>.el-overlay {
    background-color:rgba(0,0,0,0);
}*/
</style>
